Socket
Socket
Sign inDemoInstall

@apollo/react-hooks

Package Overview
Dependencies
23
Maintainers
1
Versions
30
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    @apollo/react-hooks

React Apollo Hooks.


Version published
Weekly downloads
182K
increased by6.53%
Maintainers
1
Created
Weekly downloads
 

Readme

Source

React Apollo

React Apollo - Hooks

npm version Build Status Join the community on Spectrum

React Apollo Hooks.

NOTE: Full React Apollo Hooks usage documentation is coming soon, and when ready will be made available in the main React Apollo documentation. The contents of this README are intended to help beta testers, and will change.

Contents

  1. Installation
  2. Hooks Overview
  1. Reference

Installation

npm install @apollo/react-hooks

Hooks Overview

a) useQuery

Function:

export function useQuery<TData = any, TVariables = OperationVariables>(
  query: DocumentNode,
  options?: QueryHookOptions<TData, TVariables>
): QueryResult<TData, TVariables>;

Options:

query?: DocumentNode;
displayName?: string;
skip?: boolean;
onCompleted?: (data: TData) => void;
onError?: (error: ApolloError) => void;
ssr?: boolean;
variables?: TVariables;
fetchPolicy?: WatchQueryFetchPolicy;
errorPolicy?: ErrorPolicy;
pollInterval?: number;
client?: ApolloClient<any>;
notifyOnNetworkStatusChange?: boolean;
context?: Context;
partialRefetch?: boolean;
returnPartialData?: boolean

Result:

  • client: ApolloClient;
  • data: TData | undefined;
  • error?: ApolloError;
  • loading: boolean;
  • networkStatus: NetworkStatus;
  • fetchMore: any;

Example (from the Hooks demo app):

const GET_ROCKET_INVENTORY = gql`
  query getRocketInventory {
    rocketInventory {
      id
      model
      year
      stock
    }
  }
`;

export function RocketInventoryList() {
  const { loading, data } = useQuery(GET_ROCKET_INVENTORY);
  return (
    <Row className="rocket-inventory-list mt-4">
      <Col sm="12">
        <h3>Available Inventory</h3>
        {loading ? (
          <p>Loading ...</p>
        ) : (
          <table className="table table-striped table-bordered">
            <thead>
              <tr>
                <th>Model</th>
                <th>Year</th>
                <th>Stock</th>
              </tr>
            </thead>
            <tbody>
              {data.rocketInventory.map((inventory: RocketInventory) => (
                <tr
                  key={`${inventory.model}-${inventory.year}-${
                    inventory.stock
                  }`}
                >
                  <td>{inventory.model}</td>
                  <td>{inventory.year}</td>
                  <td>{inventory.stock}</td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </Col>
    </Row>
  );
}

b) useMutation

Function:

export function useMutation<TData = any, TVariables = OperationVariables>(
  mutation: DocumentNode,
  options?: MutationHookOptions<TData, TVariables>
): MutationTuple<TData, TVariables>;

Options:

mutation?: DocumentNode;
variables?: TVariables;
optimisticResponse?: TData | ((vars: TVariables) => TData);
refetchQueries?: Array<string | PureQueryOptions> | RefetchQueriesFunction;
awaitRefetchQueries?: boolean;
errorPolicy?: ErrorPolicy;
update?: MutationUpdaterFn<TData>;
client?: ApolloClient<object>;
notifyOnNetworkStatusChange?: boolean;
context?: Context;
onCompleted?: (data: TData) => void;
onError?: (error: ApolloError) => void;
fetchPolicy?: WatchQueryFetchPolicy;
ignoreResults?: boolean;

Result:

[
  (
    options?: MutationFunctionOptions<TData, TVariables>
  ) => Promise<void | ExecutionResult<TData>>,
  {
    data?: TData;
    error?: ApolloError;
    loading: boolean;
    called: boolean;
    client?: ApolloClient<object>
  }
];

Example (from the Hooks demo app):

const SAVE_ROCKET = gql`
  mutation saveRocket($rocket: RocketInput!) {
    saveRocket(rocket: $rocket) {
      model
    }
  }
`;

export function NewRocketForm() {
  const [model, setModel] = useState('');
  const [year, setYear] = useState(0);
  const [stock, setStock] = useState(0);

  const [saveRocket, { error, data }] = useMutation<
    {
      saveRocket: RocketInventory;
    },
    { rocket: NewRocketDetails }
  >(SAVE_ROCKET, {
    variables: { rocket: { model: model, year: +year, stock: +stock } },
    refetchQueries: ['getRocketInventory']
  });

  return (
    <div className="new-rocket-form mt-3">
      <h3>Add a Rocket</h3>
      {error ? <Alert color="danger">Oh no! {error.message}</Alert> : null}
      {data && data.saveRocket ? (
        <Alert color="success">
          Model <strong>{data.saveRocket.model}</strong> added!
        </Alert>
      ) : null}
      <Form style={{ border: '1px solid #ddd', padding: '15px' }}>
        <Row>
          <Col sm="6">
            <FormGroup>
              <Label for="model">Model</Label>
              <Input
                type="text"
                name="model"
                id="model"
                onChange={e => setModel(e.target.value)}
              />
            </FormGroup>
          </Col>
          <Col sm="3">
            <FormGroup>
              <Label for="year">Year</Label>
              <Input
                type="number"
                name="year"
                id="year"
                onChange={e => setYear(+e.target.value)}
              />
            </FormGroup>
          </Col>
          <Col sm="3">
            <FormGroup>
              <Label for="stock">Stock</Label>
              <Input
                type="number"
                name="stock"
                id="stock"
                onChange={e => setStock(+e.target.value)}
              />
            </FormGroup>
          </Col>
        </Row>
        <Row>
          <Col
            sm="12"
            className="text-right"
            onClick={e => {
              e.preventDefault();
              if (model && year && stock) {
                saveRocket();
              }
            }}
          >
            <Button>Add</Button>
          </Col>
        </Row>
      </Form>
    </div>
  );
}

c) useSubscription

Function:

export function useSubscription<TData = any, TVariables = OperationVariables>(
  subscription: DocumentNode,
  options?: SubscriptionHookOptions<TData, TVariables>
);

Options:

subscription?: DocumentNode;
variables?: TVariables;
fetchPolicy?: FetchPolicy;
shouldResubscribe?: boolean | ((options: BaseSubscriptionOptions<TData, TVariables>) => boolean);
client?: ApolloClient<object>;
onSubscriptionData?: (options: OnSubscriptionDataOptions<TData>) => any;
onSubscriptionComplete?: () => void;

Example (from the Hooks demo app):

const LATEST_NEWS = gql`
  subscription getLatestNews {
    latestNews {
      content
    }
  }
`;

export function LatestNews() {
  const { loading, data } = useSubscription<News>(LATEST_NEWS);
  return (
    <Card className="bg-light">
      <CardBody>
        <CardTitle>
          <h5>Latest News</h5>
        </CardTitle>
        <CardText>{loading ? 'Loading...' : data!.latestNews.content}</CardText>
      </CardBody>
    </Card>
  );
}

d) useApolloClient

Function:

export function useApolloClient(): ApolloClient<object>;

Result:

ApolloClient instance stored in the current Context.

Example:

const client = useApolloClient();
consol.log('AC instance stored in the Context', client);

Reference

Keywords

FAQs

Last updated on 05 Aug 2019

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc